package kr.pe.mkseo.data;

import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import kr.pe.mkseo.data.persistence.CsvDataField;
import kr.pe.mkseo.data.persistence.CsvDataFile;

import com.google.common.collect.Lists;

@CsvDataFile(FileName="accounts.csv")
public class Account {
	@CsvDataField(Order=0)
	private Category category_;
	@CsvDataField(Order=1)
	private String name_;
	@CsvDataField(Order=2)
	private Date endDate_;
	@CsvDataField(Order=3)
	private List<Record> records_;
	/** If the order in balance record is tainted, i.e., need sort. */
	private boolean records_tainted_;

	// TODO: Retrieval order
	
	public Account(String name, Date endDate) {
		name_ = name;
		endDate_ = endDate;
		records_ = Lists.newArrayList();
		records_tainted_ = false;
	}
	
	public void AddBalanceRecord(Record rec) {
		records_.add(rec);
		records_tainted_ = true;
	}
	
	/**
	 * @return Unmodifiable iterator of balance records.
	 */
	public Iterator<Record> UnmodifiableIterator() {
		GuaranteeSorted();
		return com.google.common.collect.Iterators.unmodifiableIterator(
				records_.iterator());
	}

	private void GuaranteeSorted() {
		if (records_tainted_) {
			// Sort only before using data.
			Collections.sort(records_);
			records_tainted_ = false;
		}
	}
	
	public Record GetLastBalanceRecord() {
		GuaranteeSorted();
		return records_.get(records_.size() -1);
	}
	
	public String GetName() {
		return name_;
	}
	
	public Date GetEndDate() {
		return endDate_;
	}
	
	@Override
	public int hashCode() {
		return name_.hashCode() + category_.hashCode();
	}
}
